package com.scalar.forecast.forecastEntry.actionCommands;

import com.scalar.forecast.actionCommands.ActionCommand;
import com.scalar.forecast.forecastEntry.forms.ForecastEntryForm;
import com.scalar.forecast.forecastEntry.SlotData;
import com.scalar.forecast.forecastEntry.RowData;
import com.scalar.forecast.forecastEntry.TableRowBean;
import com.scalar.forecast.forecastEntry.dao.ForecastEntryDAO;
import com.scalar.forecast.forecastSetup.ForecastTimeFrame;
import com.scalar.forecast.forecastSetup.dao.ForecastSetupDAO;
import com.scalar.forecast.commons.Constants;
import com.scalar.forecast.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.db.DBXException;
import com.scalar.chiptrack.users.User;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.LinkedList;
import java.util.HashMap;

/**
 * User: Sujan Kumar
 * Date: Feb 16, 2005
 * Time: 12:34:56 PM
 */
public class ForecastEntrySalesSaveCommand extends ActionCommand
{
    public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response )
    {
        ForecastEntryForm forecastEntryForm = ( ForecastEntryForm )form;

        boolean success = false;
        DBTransaction dbTransaction = null;
        HashMap errors = new HashMap ();
        HashMap info = new HashMap ();
        HttpSession session = request.getSession();
        User pUser = ( User )session.getAttribute( SessionKeys.USER_KEY);
        try
        {
            dbTransaction = DBTransaction.getInstance();
            dbTransaction.begin();

            String userId = pUser.getUserId();
            ForecastTimeFrame timeFrame = ForecastSetupDAO.getForecastTimeFrame(null);
            LinkedList slotDataList = null;
            SlotData slotData = null;
            RowData rowData = null;
            TableRowBean tableRowBean = null;
            int salesPersonId = -1;
            LinkedList rowDataList = forecastEntryForm.getTableDataList();
            int rowDataListSize = rowDataList.size();
            String buildNo = ForecastEntryDAO.getNextBuildNo( dbTransaction ); //used when saving build forecast
            for ( int row=0; row < rowDataListSize; row++ )
            {
                rowData = ( RowData ) rowDataList.get ( row );
                if ( rowData.isSelected() )
                {
                    salesPersonId = rowData.getSalesPersonId();
                    slotDataList = rowData.getSlotDataList();
                    int slotDataListSize = slotDataList.size();
                    for ( int slot = 0; slot < slotDataListSize; slot++ )
                    {
                        slotData = ( SlotData )slotDataList.get ( slot );
                        tableRowBean = new TableRowBean();
                        tableRowBean.setSalesPersonId( salesPersonId );
                        tableRowBean.setCustId( forecastEntryForm.getCustId() );
                        tableRowBean.setProjId( forecastEntryForm.getProjectId() );
                        tableRowBean.setProductId( forecastEntryForm.getProductId() );
                        tableRowBean.setOdmId( forecastEntryForm.getOdmId() );
                        tableRowBean.setUserId ( userId );

                        tableRowBean.setRowId( slotData.getRowId() );//this is the rowId from the salesMaster table.
                        tableRowBean.setMonth ( getMonth ( slot, forecastEntryForm.getStartMonth_Quarter_Year(), timeFrame.getTfName() ) );
                        tableRowBean.setQuarter( getQuarter ( slot, forecastEntryForm.getStartMonth_Quarter_Year(), timeFrame.getTfName() ) );
                        tableRowBean.setYear ( getYear ( slot, forecastEntryForm.getStartMonth_Quarter_Year(), forecastEntryForm.getYear(), timeFrame.getTfName() ) );

                        tableRowBean.setQty( slotData.getQty() );
                        tableRowBean.setPrice( slotData.getPrice() );
                        tableRowBean.setConfidenceLevel( slotData.getConfidenceLevel() );
                        tableRowBean.setUserList1( slotData.getUserList1() );
                        tableRowBean.setUserDate1( slotData.getUserDate1() );
                        tableRowBean.setUserTxt1( slotData.getUserTxt1() );
                        tableRowBean.setUserTxt2( slotData.getUserTxt2() );

                        ForecastEntryDAO.saveSalesForecastEntry (dbTransaction, tableRowBean);
                        if ( forecastEntryForm.isBuild() )  //todo  need to save only if system parameter is set.
                        {
                            request.setAttribute ( Constants.FORECAST_IS_BUILD, "true" );
                            //todo need to upate the rowId from build table.
                            //int buildRowId = ForecastEntryDAO.getBuildMasterRowId ( dbTransaction, slot, forecastEntryForm );
                            //tableRowBean.setRowId ( buildRowId );

                            ForecastEntryDAO.saveBuildForecastEntry (dbTransaction, tableRowBean, buildNo );
                        }
                    }
                }
            }
            /* To Save Default Build Values*/
            if ( forecastEntryForm.isBuild() )
            {
                RowData buildRowData = forecastEntryForm.getBuildRowData();
                slotDataList = buildRowData.getSlotDataList();
                int slotDataListSize = slotDataList == null ? 0 : slotDataList.size();
                for ( int slot = 0; slot < slotDataListSize; slot++ )
                {
                    slotData = ( SlotData )slotDataList.get ( slot );
                    tableRowBean = new TableRowBean();
                    tableRowBean.setSalesPersonId( -1 );
                    tableRowBean.setCustId( forecastEntryForm.getCustId() );
                    tableRowBean.setProjId( forecastEntryForm.getProjectId() );
                    tableRowBean.setProductId( forecastEntryForm.getProductId() );
                    tableRowBean.setOdmId( forecastEntryForm.getOdmId() );
                    tableRowBean.setUserId ( userId );

                    tableRowBean.setRowId( slotData.getRowId() );
                    tableRowBean.setMonth ( getMonth ( slot, forecastEntryForm.getStartMonth_Quarter_Year(), timeFrame.getTfName() ) );
                    tableRowBean.setQuarter( getQuarter ( slot, forecastEntryForm.getStartMonth_Quarter_Year(), timeFrame.getTfName() ) );
                    tableRowBean.setYear ( getYear ( slot, forecastEntryForm.getStartMonth_Quarter_Year(), forecastEntryForm.getYear(), timeFrame.getTfName() ) );

                    tableRowBean.setQty( slotData.getQty() );
                    tableRowBean.setPrice( slotData.getPrice() );
                    tableRowBean.setConfidenceLevel( slotData.getConfidenceLevel() );
                    tableRowBean.setUserList1( slotData.getUserList1() );
                    tableRowBean.setUserDate1( slotData.getUserDate1() );
                    tableRowBean.setUserTxt1( slotData.getUserTxt1() );
                    tableRowBean.setUserTxt2( slotData.getUserTxt2() );
                    ForecastEntryDAO.saveBuildForecastEntry ( dbTransaction, tableRowBean, buildNo );
                }
            }
            success = true;
            if ( forecastEntryForm.isBuild() )
            {
                info.put( INFO_BUILD_FORECAST_SAVE_SUCCESSFULL + " with Build No: <strong style='color:red;'>" + buildNo + "</strong>", null );
            }
            else
            {
                info.put( INFO_SALES_FORECAST_SAVE_SUCCESSFULL, null );
            }
            request.setAttribute( SessionKeys.INFO_MESSAGES, info );
        }
        catch ( Exception e )
        {
            errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_COULD_NOT_SAVE_FORECAST );
            request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
            System.out.println ( "--Exception while saving forecast entry--" );
            e.printStackTrace();
        }
        finally
        {
            if ( dbTransaction != null )
            {
                try
                {
                    if ( success )
                    {
                        dbTransaction.commit();
                    }
                    else
                    {
                        dbTransaction.rollback();
                    }
                }
                catch ( DBXException e )
                {
                    System.out.println ( "--DBX Exception while committing/rollbacking..." );
                }
            }
        }

        //session.removeAttribute( "forecastEntryForm" );
		session.removeAttribute ( mapping.getName() );
        ActionForward actionForward = null;
        actionForward = mapping.findForward ( "saveSuccess" );

        return actionForward;
    }
    public int getMonth ( int slot, int startMonth, String timeFrame )
    {
        int month = -1;
        if ( Constants.FORECAST_TIMEFRAME_MONTH.equalsIgnoreCase( timeFrame ) )
        {
            month = ( slot + startMonth ) % 12;
        }
        return month;
    }
    public int getQuarter ( int slot, int startQuarter, String timeFrame )
    {
        int quarter = -1;
        if ( Constants.FORECAST_TIMEFRAME_QUARTER.equalsIgnoreCase( timeFrame ) )
        {
            quarter = ( slot + startQuarter ) % 4;
        }
        return quarter;
    }
    public int getYear ( int slot, int start, int year, String timeFrame )
    {
        int resultYear = -1;
        if ( Constants.FORECAST_TIMEFRAME_MONTH.equalsIgnoreCase( timeFrame ) )
        {
            int startMonth = start;
            int yearCnt = ( slot + startMonth ) / 12;
            resultYear = year + yearCnt;
        }
        if ( Constants.FORECAST_TIMEFRAME_QUARTER.equalsIgnoreCase( timeFrame ) )
        {
            int startQuarter = start;
            int yearCnt = ( slot + startQuarter ) / 4;
            resultYear = year + yearCnt;
        }
        if ( Constants.FORECAST_TIMEFRAME_YEAR.equalsIgnoreCase( timeFrame ) )
        {
            int startYear = start;
            resultYear = startYear + slot;
        }
        return resultYear;
    }
}
